<?php

namespace Rexzy\Tool;
class Cookie {
    
    private $_slat = '';
    private $_request;
    private $_path;
    private $_domain;
    
    public function __construct( $slat = null, $path = null, $domain = null ) {
        if ( $slat == null ) {
            $this->_slat = \Rexzy::getConfig( 'slat' );
        } else {
            $this->_slat = $slat;
        }
        if ( $path == null) {
            $this->_path = \Rexzy::getConfig( 'cookie_path' );
        } else {
            $this->_path = $path;
        }
        if ( $domain == null ) {
            $this->_domain = \Rexzy::getConfig( 'cookie_domain' );
        } else {
            $this->_domain = $domain;
        }
        
        $this->_request = \Rexzy\Http\Request::getInstance();        
    }
    
    /**
     *  设置cookie 
     * 
     * @param string $name cookie名称
     * @param string $value cookie值
     * @param int $expire 设置cookie的有效时间
     */
    public function set( $name, $value = null, $expire = 0 ) {
        setcookie( $name, $value, time() + $expire, $this->_path, $this->_domain);
        setcookie( $name . '_hash', md5( $value . $this->_slat ), time() + $expire, $this->_path, $this->_domain);
    }
    
    /**
     * 查询提交的cookie 格式是否正确
     * 
     * @param string $name 查询的cookie 键值名
     * @return mixed 如果提交的是正确的cookie格式，返回cookie值，否则返回空
     */
    public function get( $name ) {
        $request_value = $this->_request->input( $name, 'c' );
        $request_value_hash = $this->_request->input( $name . '_hash', 'c' );
        if ( ( ! $request_value ) || ( ! $request_value_hash ) ) {
            return null;
        }
        $true_value_hash = md5( $request_value . $this->_slat );
        if( $request_value_hash === $true_value_hash ) {
            return $request_value;
        }
        return null;
    }
}
